package com.stefan.framework.protocol.http;

import com.stefan.framework.Invocation;
import com.stefan.framework.LocalRegister;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//handler类去处理请求
public class HttpServerHandler {
    public void handle (HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //这里拿到请求的内容后，去调用对应的服务，怎么调用服务呢？是不是应该通过interfaceName（服务名）去查找对应的服务提供者？
        //这里就需要服务启动的时候去注册一个服务提供者的列表，或者说是服务注册中心
        //假设我们有一个LocalRegister类，它可以根据interfaceName获取对应的服务实例

        try {
            ObjectInputStream ois = new ObjectInputStream(req.getInputStream());
            Invocation invocation = (Invocation)ois.readObject();

            String interfaceName = invocation.getInterfaceName();
            String methodName = invocation.getMethodName();
            Class<?>[] parameterTypes = invocation.getParameterTypes();
            Object[] arguments = invocation.getArguments();
            //获取服务class
            Class service = LocalRegister.getService(interfaceName);
            Method method = service.getMethod(methodName, parameterTypes);
            String result = (String)method.invoke(service.newInstance(), arguments);
            //将结果写入响应
            IOUtils.write(result,resp.getOutputStream());
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
